package com.jike.jkgame.data;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.jike.jkgame.Utilis;
import com.jike.jkgame.db.ResourcesDAO;

public class Skill {
	public int id;
	public String descript;
	public byte attack_addon;
	public byte defense_addon;
	public byte strength_addon;
	public byte country;
	public byte country_addon;
	public byte opponent;
	public byte opponent_addon;
	public SkillCondition[] condition;
	
	public static class SkillCondition {
		public int id;
		public byte type;
		
		/* [id,type]
		 * @see java.lang.Object#toString()
		 */
		@Override
		public String toString() {
			return "[" + String.valueOf(id) + "," + String.valueOf(type) + "]";
		}

		public static SkillCondition fromString(String str) {
			
			if (str.startsWith("[") && str.endsWith("]")) {
				String subStr = str.substring(1, str.length()-1);
				SkillCondition condition = new SkillCondition();
				String[] subs = subStr.split(",");
				condition.id = Integer.valueOf(subs[0]);
				condition.type = Byte.valueOf(subs[1]);
				
				return condition;
			}
			
			return null;
		}
		
		public static SkillCondition[] stringToArray(String str) {
			if (str == null) {
				return null;
			}
			
			String[] itemStrs = str.split(Utilis.SEPERATOR);
			SkillCondition[] items = new SkillCondition[itemStrs.length];
			for (int i=0; i<itemStrs.length; ++i) {
				items[i] = SkillCondition.fromString(itemStrs[i]);
			}
			
			return items;
		}
	}
	
	private static Skill parseSkill(DataInputStream dis, byte[] buff) {
		Skill skill = new Skill();
		
		try {
			skill.id = dis.readInt();
			skill.descript = Utilis.getString(dis, buff);
			skill.attack_addon = dis.readByte();
			skill.defense_addon = dis.readByte();
			skill.strength_addon = dis.readByte();
			skill.country = dis.readByte();
			skill.country_addon = dis.readByte();
			skill.opponent = dis.readByte();
			skill.opponent_addon = dis.readByte();
			int cnt = dis.readInt();
			skill.condition = new SkillCondition[cnt];
			
			for (int i=0; i<cnt; ++i) {
				SkillCondition condition = new SkillCondition();
				condition.id = dis.readInt();
				condition.type = dis.readByte();
				
				skill.condition[i] = condition;
			}
			
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
		return skill;
	}
	
	public static int parseDataFile(InputStream in) {
		DataInputStream dis = new DataInputStream(in);
		int count  = 0;
		
		ResourcesDAO dao = ResourcesDAO.get();
		byte[] buff = new byte[4096];
		
		try {
			int type = dis.readInt();
			int version = dis.readInt();
			
			int myVersion = dao.getDataFileVersion(type);
			
			if (myVersion >= version) {
				return 0;
			}
			
			dao.clearSkills();
			Skill s = null;
			do {
				s = parseSkill(dis, buff);
				dao.insertSkill(s);
				count++;
			}while(s != null);
			dao.updateDataFileVersion(type, version);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return count;
		
	}
	
	
}
